{# SPDX-FileCopyrightText: © 2020 Siemens AG

   SPDX-License-Identifier: FSFAP
#}

function checkpassword() {
  var policyRegex = /^{{ policyRegex }}$/m;
  var passField = $('#passcheck');
  var pass = passField.val();
  if (pass.match(policyRegex)) {
    passField.removeClass('passFail');
    passField.addClass('passPass');
    return true;
  }
  passField.removeClass('passPass');
  passField.addClass('passFail');
  return false;
}

function checkpasswordmatch() {
  var pass1 = $('#passcheck').val();
  var pass2Field = $('#pass2');
  if (checkpassword() && pass2Field.val() === pass1) {
    pass2Field.removeClass('passFail');
    pass2Field.addClass('passPass');
    return true;
  }
  pass2Field.removeClass('passPass');
  pass2Field.addClass('passFail');
  return false;
}

$(document).ready(function () {
  $('#passcheck').on('keyup', checkpassword);
  if ($('#pass2').length) {
    $('#pass2').on('keyup', checkpasswordmatch);
  }
  $("form[name={{ formName }}]").submit(function(e) {
    if ({{ policyDisabled }} && $('#passcheck').val() == "") {
      return true;
    }
    if (checkpassword() && checkpasswordmatch()) {
      return true;
    }
    if ($('#passwdBanner').length == 0) {
      var banner = $("<div id='passwdBanner' />").text("Please check password.");
      $("body").append(banner);
      $("#passwdBanner").dialog({
        autoOpen: false,
        height: "auto",
        width: "auto",
        title: "Password check fail",
        modal: true,
        buttons: [
          {
            text: "Ok",
            click: function() {
              $(this).dialog("close");
            }
          }
        ],
        close: function() {
          $('#passcheck').focus();
        }
      });
    }
    $("#passwdBanner").dialog("open");
    e.preventDefault();
  });
});
